/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package utain.xmlfilesearcher;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Nut
 */
public class UtainXMLFileSearcher {

    public static void main(String[] args) {
        // TODO code application logic here
        UtainXMLFileSearcher uxFs = new UtainXMLFileSearcher();
        try {
            String[] list = uxFs.getKeyWord();
            uxFs.checkXML(list);
        } catch (Exception x) {
            x.printStackTrace();
        }
    }

    private String[] getKeyWord() throws Exception {
        ArrayList<String> list = new ArrayList<String>();
        BufferedReader br = new BufferedReader(new FileReader("key.txt"));
        String tmp;
        while ((tmp = br.readLine()) != null) {
            list.add(tmp);
        }
        br.close();

        String[] StringArray = new String[list.size()];
        StringArray = list.toArray(StringArray);

        return StringArray;
    }

    private void checkXML(String[] list) throws Exception {
        File fXmlFile = new File("quotes.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        NodeList qt = doc.getElementsByTagName("quote");

        for (String list1 : list) {
            for (int i = 0; i < qt.getLength(); i++) {
                Element item = (Element) qt.item(i);
                if (getEleVal(item, "by").contains(list1)) {
                    System.out.println(getEleVal(item, "words") + " by " + getEleVal(item, "by"));
                }
            }
        }

    }

    protected String getEleVal(Element parent, String label) {
        Element e = (Element) parent.getElementsByTagName(label).item(0);
        try {
            Node child = e.getFirstChild();
            if (child instanceof CharacterData) {
                CharacterData cd = (CharacterData) child;
                return cd.getData();
            }
        } catch (Exception ex) {

        }
        return "";
    }
}
